package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class ClientResponseThread implements Runnable {

    private final ClientApp app;
    private ClientTransport transport;
    private static Queue<String> responses = new LinkedBlockingQueue<>();
    private static Object queueMonitor = new Object();

    public ClientResponseThread(ClientApp app, ClientTransport transport) {
        this.app = app;
        this.transport = transport;
    }

    @Override
    public void run() {
        while (true) {
            String message = null;
            try {
                message = transport.readLine();
                if (isMessage(message)) {
                    app.print(message.substring(4));
                } else {
                    addToResponses(message);
                }
            } catch (SocketException e) {
                System.out.println("Connection to server was closed");
                BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
                while (true) {
                    System.out.println("trying to reconnect...");
                    if (transport.tryToReconnect())
                        break;
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }

    public static String getFromResponses() throws InterruptedException {
        synchronized (queueMonitor) {
            if (responses.isEmpty()) {
                queueMonitor.wait();
            }
            return responses.remove();
        }
    }

    public void addToResponses(String message) {
        synchronized (queueMonitor) {
            responses.add(message.substring(4));
            queueMonitor.notify();
        }
    }

    public boolean isMessage(String str) {
        return str.toLowerCase().startsWith("mes ");
    }


}